package com.github.codemperor.gateway.fitler;

import com.github.codemperor.core.token.CurrentUserInfo;
import com.github.codemperor.gateway.config.BaseFilter;
import com.github.codemperor.gateway.config.ZuulConstants;
import com.github.codemperor.gateway.context.FilterContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author codemperor
 * @description 这里过滤本次请求是否通过，也可以过滤请求次数、限流等等
 */
@Component
@Slf4j
public class ApiFilter extends BaseFilter {

//    @Autowired
//    private AuthSDK authSDK;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return ZuulConstants.API_FILTER;
    }

    @Override
    public boolean shouldFilter() {
        return FilterContext.apiFilterEnabled.get();
    }

    @Override
    public Object run() {

        CurrentUserInfo user = FilterContext.currentUserInfo.get();
        if (StringUtils.isEmpty(user.getUserId())) { // token过滤可能出现错误，比如过期，导致用户信息为空，传到这里，判断一下，为空就继续往下走
            return null;
        }

        //这里判定用户是否有权限访问api
//        ApiAndUserRoleValidResponse apiRes = authSDK.apiAndUserRoleValid(user.getUri(), Long.valueOf(user.getUserId()));

//        user.setApiType(apiRes.getType());
//        user.setApiRoleList(apiRes.getApiRoleList().stream().map(String::valueOf).collect(Collectors.toList()));

//        if (!apiRes.getUserHasPermission()) {
//            FilterContext.endingException.set(BaseCodeEnum.FORBIDDEN);
//        }

        return null;
    }
}
